package zhexian.app.smartcall.contact;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import zhexian.app.smartcall.base.Const;
import zhexian.app.smartcall.tools.UploadUtil;

/**
 * Created by hling on 2015/10/11.
 * 此类用于异步上传时的回调消息缓存，解决在转屏等Activity暂时丢失时的消息丢失并导致UI发生异常的问题。
 */
public final class CachedUploadListener implements UploadUtil.OnUploadProcessListener{

    private static final String TAG = CachedUploadListener.class.getSimpleName();

    private static CachedUploadListener _instance = new CachedUploadListener();

    private volatile Handler.Callback _handler = null;

    private BlockingQueue<Message> msgQueue;

    {
        msgQueue = new LinkedBlockingQueue<Message>();
    }

    private CachedUploadListener() {
    }

    public static CachedUploadListener getInstance() {
        return _instance;
    }

    /**
     * 设置最终的Listener。本对象在最终的Listener和被监听的对象之间建立一个缓冲区
     */
    public void setUploadMessageHandler(Handler.Callback handler) {
        boolean needSendFromQueue = false;
        if (_handler != handler && handler != null ){
            needSendFromQueue = true;
        }
        _handler = handler;

        // 向新的Handler发送缓存的消息
        if (needSendFromQueue && !msgQueue.isEmpty()) {
            Log.i(TAG, "开始发送缓存的消息，消息数量：" + msgQueue.size());
            Message msg;
            while((msg = msgQueue.poll()) != null){
                _handler.handleMessage(msg);
            }
        }

    }

    @Override
    public void onUploadDone(int responseCode, String message) {
        Log.i(TAG, "上传结束");
        Message msg = Message.obtain();
        msg.what = Const.UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
        if (_handler != null) {
            _handler.handleMessage(msg);
        } else {
            msgQueue.add(msg);
        }

    }

    @Override
    public void onUploadProcess(int uploadSize) {
        Message msg = Message.obtain();
        msg.what = Const.UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
        if (_handler != null) {
            _handler.handleMessage(msg);
        } else {
            msgQueue.add(msg);
        }
    }

    @Override
    public void initUpload(int fileSize) {
        Log.i(TAG, "文件总尺寸为" + fileSize);
        Message msg = Message.obtain();
        msg.what = Const.UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
        if (_handler != null) {
            _handler.handleMessage(msg);
        } else {
            msgQueue.add(msg);
        }
    }

}
